package com.xr.blog.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sun.scenario.effect.impl.sw.sse.SSEBlend_SRC_OUTPeer;
import com.xr.blog.pojo.BlogComment;
import com.xr.blog.service.BlogCommentService;
import com.xr.blog.service.BlogConfigService;
import com.xr.blog.tools.Result;
import com.xr.blog.tools.ValidatorUtils;
import com.xr.blog.tools.constant.Code;
import com.xr.blog.tools.enums.CommentStatusEnum;
import com.xr.blog.tools.enums.CommentTargetTypeEnum;
import com.xr.blog.tools.ip.IpUtils;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Update;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;


/**
 * 评论表
 *
 * @author XRJ
 * @email 1033835209@qq.com
 * @date 2020-07-16 12:37:49
 */
@RestController
@RequestMapping("/squirrelblog")
public class BlogCommentController {

    @Autowired
    BlogCommentService blogCommentService;

    @Autowired
    private BlogConfigService configService;

    /**
     * 获得最新的n条评论
     * @param number 获取的数量
     * @return
     */
    @GetMapping(value = "/comment/latest",produces = "application/json;charset=UTF-8")
    public Result<List<BlogComment>> latest(Integer number) {
        List<BlogComment> commentList=blogCommentService.findLatestComments(number,true);
        return Result.of(Code.SC_OK.getState(),"查询成功",commentList);
    }


    /**
     * 获得最近一周评论数和总评论数
     * @return
     */
    @GetMapping(value = "/comment/commentCount",produces = "application/json;charset=UTF-8")
    public Result<Map<String,Integer>> commentCount(){
        Map<String,Integer> data=new HashMap<>();
        int totalComment= blogCommentService.count();
        data.put("totalComment",totalComment);
        int latestComment=blogCommentService.count(new QueryWrapper<BlogComment>().apply("create_time > DATE_SUB(CURDATE(), INTERVAL 1 WEEK)"));
        data.put("latestComment",latestComment);
        return Result.of(Code.SC_OK.getState(),"获取成功",data);
    }


    /**
     * 加载评论
     * @param current 需要加载的页数
     * @param size 需要加载的数量
     * @param articleId 文章ID
     * @return
     */
    @PostMapping(value = "/comment/more",produces = "application/json;charset=UTF-8")
    public List<BlogComment> commentPage(int current, int size, long articleId){
        return blogCommentService.findPageByArticleId(new Page<>(current,size,false),articleId).getRecords();
    }


    /**
     * 保存或更新评论
     * @param comment 评论的内容
     * @param request
     * @return
     */
    @PostMapping(value = "/comment/save",produces = "application/json;charset=UTF-8")
    public Result<BlogComment> save(@RequestBody @Validated(Insert.class) BlogComment comment, HttpServletRequest request) {
//        ValidatorUtils.validate(comment);
        if (comment.getTargetType().equals(CommentTargetTypeEnum.COMMENT.getValue())) {
            if (Objects.isNull(comment.getParentId())) {
                BlogComment targetComment = blogCommentService.getById(comment.getTargetId());
                comment.setReplyUserName(targetComment.getAuthor());
            } else {
                BlogComment parentComment = blogCommentService.getById(comment.getParentId());
                comment.setReplyUserName(parentComment.getAuthor());
            }
        }
        if (Objects.isNull(comment.getId())) {
            Boolean isCheck = configService.getConfigObject(Code.COMMENT_CHECK, Boolean.class);
            comment.setStatus(isCheck ? CommentStatusEnum.CHECKING.getValue() : CommentStatusEnum.PUBLISHED.getValue());
            //评论不成功，是因为user为空(取消登录才能评论的逻辑)
//            User user = (User) request.getSession().getAttribute(Const.USER_SESSION_KEY);
//            comment.setUserId(user.getId());
            comment.setUserAgent(request.getHeader("user-agent"));
            comment.setIp(IpUtils.getIpAddr(request));
            comment.setEmailMd5(DigestUtils.md5Hex(comment.getEmail()));
            blogCommentService.save(comment);
        } else {
            comment.setEmailMd5(DigestUtils.md5Hex(comment.getEmail()));
            blogCommentService.updateById(comment);
        }
        //blogCommentService.clearCache();
        return Result.of(Code.SC_OK.getState(),"操作成功",comment);
    }


    /**
     * 通过id修改评论状态
     * @param comment 评论的内容
     * @param request
     * @return
     */
    @PutMapping(value = "/comment/update",produces = "application/json;charset=UTF-8")
    public Result update(@RequestBody @Validated(Update.class) BlogComment comment, HttpServletRequest request) {
        return Result.of(Code.SC_OK.getState(),"操作成功",blogCommentService.updateById(comment));
    }

    /**
     * 通过id查询评论
     * @param id 评论id
     * @return
     */
    @GetMapping(value = "/comment/getByid",produces = "application/json;charset=UTF-8")
    public Result<BlogComment> info(Long id){
        return Result.of(Code.SC_OK.getState(),"查询成功",blogCommentService.findCommentById(id));
    }


    @GetMapping(value = "/comment/list",produces = "application/json;charset=UTF-8")
    public Result<IPage<BlogComment>> list(Page<BlogComment> page,
                                           @RequestParam(value = "content",required = false)String content,
                                           @RequestParam(value = "status",required = false)Integer status,
                                           @RequestParam(value = "targetType",required = false)Integer targetType) {
        QueryWrapper<BlogComment> queryWrapper=new QueryWrapper<>();
        if(status==null){
            queryWrapper.ne("status",2);
        }else{
            queryWrapper.eq("status",status);
        }
        if(targetType!=null){
            queryWrapper.eq("target_type",targetType);
        }
        if(StringUtils.isNotBlank(content)){
            queryWrapper.like("content",content);
        }
        IPage<BlogComment> commentPage=blogCommentService.findCommentsByPage(page,queryWrapper);

        return Result.of(Code.SC_OK.getState(),"查询成功",commentPage);
    }

}
